package com.jn.touchdemo.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.jn.touchdemo.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class SignatureView extends View {

    public static final String TAG = "SignatureView";
    private Path mPath = new Path();
    private Paint mPaint = new Paint();

    private List<Path> paths = new ArrayList<>();
    private List<Paint> paints = new ArrayList<>();

    //位图的绘制内容输出者：画布
    private Canvas mCanvas;
    //用来存放绘制内容的位图
    private Bitmap mCacheBitmap;
    //上下文
    private Context mContext;

    public SignatureView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
        mContext = context;
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(10);
        mPaint.setColor(getResources().getColor(R.color.red, null));

    }
    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(5f);
    }
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mCacheBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mCacheBitmap);
        mCanvas.drawColor(Color.WHITE);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int actionIndex = event.getActionIndex();
        int actionMasked = event.getActionMasked();

        switch (actionMasked) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:
                Path path = new Path();
                path.moveTo(event.getX(actionIndex), event.getY(actionIndex));
                paths.add(path);

                Paint newPaint = new Paint(mPaint);
                paints.add(newPaint);
                break;

            case MotionEvent.ACTION_MOVE:
                for (int i = 0; i < event.getPointerCount(); i++) {
                    int pointerIndex = event.findPointerIndex(i);
                    // 确保路径列表中有足够的路径对象
                    if (i < paths.size()) {
                        paths.get(i).lineTo(event.getX(pointerIndex), event.getY(pointerIndex));
                    }
                }
                invalidate();
                break;

            // 移除以下 case 块，以防止在 ACTION_UP、ACTION_POINTER_UP 和 ACTION_CANCEL 时移除路径
            // case MotionEvent.ACTION_UP:
            // case MotionEvent.ACTION_POINTER_UP:
            // case MotionEvent.ACTION_CANCEL:
            //     paths.remove(actionIndex);
            //     paints.remove(actionIndex);
            //     invalidate();
            //     break;
        }
        return true;
    }



    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.e(TAG, "onDraw canvas = " + canvas);

        for (int i = 0; i < paths.size(); i++) {
            canvas.drawPath(paths.get(i), paints.get(i));
        }
    }

    /**
     * 清空
     */
    public void clear() {
        Log.e(TAG, "clear()");

        // 清空路径列表和画笔列表
        paths.clear();
        paints.clear();

        // 重置画布背景为白色
        if (mCanvas != null) {
            mCanvas.drawColor(Color.WHITE);
        }

        // 请求重新绘制视图
        invalidate();
    }


    public void save() {
        //创建一个文件用于存放图片
        File file = new File(mContext.getExternalFilesDir(null) + "testSign.png");
        if (file.exists()) {
            file.delete();
        }
        OutputStream outputStream = null;
        try {
            //输出到这个文件
            outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(mContext, "保存异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        //压缩形成输出流
        mCacheBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        Toast.makeText(mContext, "保存成功!path:" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
    }

    public void saveImageToGallery() {
        String savedImageURL = MediaStore.Images.Media.insertImage(
                mContext.getContentResolver(),
                mCacheBitmap,
                "testSign",
                "testSign save"
        );
        Toast.makeText(mContext, "保存成功! URL:" + savedImageURL, Toast.LENGTH_SHORT).show();
    }
}